<template>
  <el-dialog
    :title="$t('domainlist.selectTemplate')"
    :visible="internalVisible"
    width="90%"
    custom-class="select-template-dialog"
    center
    @open="onOpen"
    @close="handleCancel"
  >
    <el-form :model="localForm" label-width="80px">
      <el-form-item :label="$t('domainlist.templateSelect')">
        <el-select v-model="localForm.templateName" :placeholder="$t('domainlist.templateSelect')">
          <el-option v-for="(val, key) in configsData" :key="key" :label="key" :value="key" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="localForm.templateName && localForm.templateName.includes('60')" label="指定语言">
        <el-select v-model="localForm.language" placeholder="默认英文">
          <el-option label="英文" value="en" />
          <el-option label="日文" value="jp" />
          <el-option label="韩文" value="kr" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">{{ $t('domainlist.cancel') }}</el-button>
      <el-button type="primary" @click="handleConfirm">{{ $t('domainlist.confirmPush') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
export default {
  name: 'SelectTemplate',
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    configsData: {
      type: Object,
      required: true
    },
    modelValue: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      localForm: {
        templateName: this.modelValue,
        language: undefined
      }
    }
  },
  computed: {
    internalVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    modelValue(newVal) {
      this.localForm.templateName = newVal
    },
    localForm: {
      handler(newVal) {
        this.$emit('update:modelValue', newVal.templateName)
      },
      deep: true
    }
  },
  methods: {
    onOpen() {
      this.localForm.templateName = this.modelValue
    },
    handleCancel() {
      this.internalVisible = false
    },
    handleConfirm() {
      const load = {
        templateName: this.localForm.templateName,
        language: this.localForm.templateName.includes('60')
          ? this.localForm.language || undefined
          : undefined
      }
      this.$emit('confirm', load)
      this.internalVisible = false
    }
  }
}
</script>

<style>
.select-template-dialog {
  max-width: 400px;
  margin-left: auto;
  margin-right: auto;
}
</style>
